package hxy.ecnu.controller;

import hxy.ecnu.model.BaseResponse;
import hxy.ecnu.model.User;
import hxy.ecnu.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	private final static Logger logger = LoggerFactory.getLogger(UserController.class);

	//	@Resource //JSR-250提供的注解
	@Autowired //Spring5提供的注解
	private UserService userService;

	@GetMapping("/findAll") //Spring5才提供GetMapping注解
	@ResponseBody
	public ArrayList<User> findAll(Model model) {
		ArrayList<User> aList = userService.findAll();
//		System.out.println("查询得到的数组长度："+aList.size());
		logger.info(String.format("查询得到的数组长度：%s", aList.size()));
		for (User user : aList) {
			System.out.println("id" + user.getId() + "name" + user.getName());
		}
		return aList;
	}

	@GetMapping("/findById")
	public String findById(Model model) {
//        User ayRole = UserService.findById("1");
		int a=1/0;
		return "success";
	}
	
	@GetMapping("/addUser")
	@ResponseBody
	public BaseResponse<User> addUser( @RequestParam(value="name") String name,@Validated @RequestParam(value="password") String password) {
		User user = new User();
		user.setName(name);
		user.setPassword(password);
		userService.insert(user);
		
		return new BaseResponse<User>(200, "插入成功", user);
	}

	@GetMapping("/index")
	public String index(Model model) {

		// 返回index.jsp视图
		return "index";
	}
	/**
	 * 请求方法不支持，不知道为啥
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public  BaseResponse<Integer> deleteUser(@PathVariable("id") String id) {
		int msg = userService.deleteUserById(id);
		
//		logger.info(msg);
		return new BaseResponse<Integer>(200, "删除成功", msg);
	}
}
